package com.steven.treatment_nurse.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.chat.EMClient;
import com.steven.treatment_nurse.R;
import com.steven.treatment_nurse.adapter.HSBedRecycleAdapter;
import com.steven.treatment_nurse.base.BaseActivity;
import com.steven.treatment_nurse.breadCast.CallReceiver;
import com.steven.treatment_nurse.customprovider.GridItemDecoration;
import com.steven.treatment_nurse.entity.CallState;
import com.steven.treatment_nurse.entity.HSBedEntity;
import com.steven.treatment_nurse.entity.ResultEntity;
import com.steven.treatment_nurse.net.MyCallback;
import com.steven.treatment_nurse.net.TaskNoHead;
import com.steven.treatment_nurse.utils.SPUtils;
import com.steven.treatment_nurse.utils.TimeUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import retrofit2.Response;

public class HSBedOverActivity extends BaseActivity implements CallState {
    @BindView(R.id.recycle_view)
    RecyclerView recycler_view;
    @BindView(R.id.tv_week)
    TextView tvWeek;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_hs_bed)
    TextView tv_hs_bed;
    @BindView(R.id.rel_bottom)
    RelativeLayout rel_bottom;
    @BindView(R.id.rel_load)
    RelativeLayout rel_load;
    private int count = 0;
    private TimeReceive timeReceive;
    private List<HSBedEntity> hsBedEntities = new ArrayList<>();
    private HSBedRecycleAdapter hsBedRecycleAdapter;
    private CallReceiver callReceiver;
    @Override
    public int intiLayout() {
        return R.layout.activity_hs_bed;
    }

    @Override
    public void initView() {
        callReceiver=new CallReceiver();
        IntentFilter callFilter = new IntentFilter(EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
        registerReceiver(callReceiver, callFilter);
        timeReceive = new TimeReceive();
        tvWeek.setText(Objects.requireNonNull(TimeUtil.getTime()).get(2));
        tvDate.setText(TimeUtil.getTime().get(0));
        tvTime.setText(TimeUtil.getTime().get(1));
        IntentFilter s_intentFilter;
        s_intentFilter = new IntentFilter();
        s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
        s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
        registerReceiver(timeReceive, s_intentFilter);

        initRecycle();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeReceive != null) {
            unregisterReceiver(timeReceive);
        }
        if (callReceiver!=null){
            unregisterReceiver(callReceiver);
        }
    }

    private void initRecycle() {
        hsBedRecycleAdapter = new HSBedRecycleAdapter(hsBedEntities);
        hsBedRecycleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (hsBedEntities.get(position).getName() != null && !hsBedEntities.get(position).getName().equals("")) {
                    Intent it = new Intent(HSBedOverActivity.this, HSBedDetailActivity.class);
                    it.putExtra("hs", hsBedEntities.get(position));
                    startActivity(it);
                }

            }
        });
//        recycler_view.setHasFixedSize(true);
        GridItemDecoration divider = new GridItemDecoration.Builder(this)
                .setHorizontalSpan(R.dimen.dp2)
                .setVerticalSpan(R.dimen.dp2)
                .setColorResource(R.color.transparent)
                .setShowLastLine(false)
                .build();
//        recycler_view.setNestedScrollingEnabled(false);
//        GridLayoutManager staggeredGridLayoutManager = new GridLayoutManager(this, 6);
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(10, StaggeredGridLayoutManager.VERTICAL);
//        manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
//        LinearLayoutManager manager = new LinearLayoutManager(this);


//        recycler_view.setHasFixedSize(true);
//        recycler_view.setItemViewCacheSize(18);
//        recycler_view.setDrawingCacheEnabled(true);
//        recycler_view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

        recycler_view.setLayoutManager(manager);
        recycler_view.addItemDecoration(divider);
        recycler_view.setAdapter(hsBedRecycleAdapter);


//        //设置layoutManager
//        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(6, StaggeredGridLayoutManager.VERTICAL);
////解决item跳动
////        manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
//
//        TestAdapter mAdapter = new TestAdapter(this, hsBedEntities, new TestAdapter.flashCallBack() {
//            @Override
//            public void onItemClick(int position) {
//                startActivity(new Intent(HSBedOverActivity.this,HSDetailActivity.class));
//            }
//        });
//
//        recycler_view.setAdapter(mAdapter);
//        recycler_view.setLayoutManager(manager);
//        mAdapter.notifyDataSetChanged();
        getBedList();
    }

    //获取床位列表
    private void getBedList() {
        rel_load.setVisibility(View.VISIBLE);
        String token = SPUtils.get(this, "token", "") + "";
        TaskNoHead.getInstance().getBedList(token).enqueue(new MyCallback<ResultEntity>() {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(Response response) {
                try {
                    JSONObject jsonObject = (JSONObject) JSONObject.toJSON(response.body());
                    assert jsonObject != null;
                    if (jsonObject.getInteger("code") == 0) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            HSBedEntity hsBedEntity = new HSBedEntity();
                            hsBedEntity.setHsBed(jsonObject1.getString("name"));
                            if (jsonObject1.getJSONObject("batch") != null) {
                                count++;
                                JSONObject jsonObject2 = jsonObject1.getJSONObject("batch");
                                hsBedEntity.setId(jsonObject2.getInteger("id"));
                                hsBedEntity.setName(jsonObject2.getString("name"));
                                hsBedEntity.setPhone(jsonObject2.getString("phone"));
                                hsBedEntity.setAge(jsonObject2.getInteger("age") + "岁");
                                hsBedEntity.setSex(jsonObject2.getString("sex"));
                                hsBedEntity.setAdmissionTime(jsonObject2.getString("create_time").substring(0, 10));
                                hsBedEntity.setBirthDate("出生年月：2020-03-15");
                                hsBedEntity.setCaseHS(jsonObject2.getString("case"));
                            }
                            hsBedEntity.setCallState(Normal);
                            hsBedEntities.add(hsBedEntity);
                        }
                        hsBedRecycleAdapter.notifyDataSetChanged();
                        tv_hs_bed.setText("床位使用：" + count + "/" + jsonArray.size());
                        rel_bottom.setVisibility(View.VISIBLE);
                        rel_load.setVisibility(View.GONE);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    rel_load.setVisibility(View.GONE);
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                rel_load.setVisibility(View.GONE);
            }
        });
    }


    private class TimeReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                tvWeek.setText(Objects.requireNonNull(TimeUtil.getTime()).get(2));
                tvDate.setText(TimeUtil.getTime().get(0));
                tvTime.setText(TimeUtil.getTime().get(1));
            }
        }
    }


}
